#pragma once
#include "Socket.hpp"
#include "Log.hpp"
#include "Connection.hpp"
#include <memory>
#include "IOService.hpp"
using namespace socket_ns;
class Listener
{
public:
    Listener(uint16_t port) : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        InetAddr svraddr("0",port);
        _listensock->BuildListenSocket(svraddr);
    }
    ~Listener()
    {
        _listensock->Close();
    }
    void Accepter(Connection *conn)
    {
        while (true)
        {
            int code = 0;
            InetAddr clientaddr;
            int sockfd = _listensock->Accepter(&clientaddr, &code);
            if (sockfd >= 0)
            {
                // 添加新连接
                conn->_R->AddConnection(sockfd,
                                        EPOLLIN | EPOLLET,
                                        IOService::HandlerRecv,
                                        IOService::HandlerSend,
                                        IOService::HandlerExcept);
                LOG(DEBUG, "accepter new link! sockfd:%d\n", sockfd);
            }
            else
            {
                if (code == EWOULDBLOCK || code == EAGAIN)
                {
                    LOG(DEBUG, "listensock accepter all link!\n");
                    break;
                }
                else if (code == EINTR)
                {
                    LOG(DEBUG, "accepter interrupted by the signal!\n");
                    continue;
                }
                else
                {
                    LOG(WARNING, "accepter error!\n");
                    break;
                }
            }
        }
    }
    int Sockfd()
    {
        return _listensock->SockFd();
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};